<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class League_model extends CI_Model
{
    public function __construct() 
    { 
        parent::__construct(); 
    }
    
    /*
     * Pobiera listę aktywnych lig z bazy danych i porządkuje ją wg kolejności nazw miast w alfabecie,
     * nazw rozgrywek w alfabecie oraz nazw lig w alfabecie
     * 
     * @return array
     */
    public function get_leagues()
    {
        $wynik = $this->db->order_by('city_name','asc')->order_by('comp_name','asc')->order_by('league_name','asc')->get('view_leagues');
        if($wynik->num_rows())
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $l)
            {
                $tab['wynik'][$l['city_id']]['name'] = $l['city_name'];
                $tab['wynik'][$l['city_id']]['code'] = $l['city_code'];
                $tab['wynik'][$l['city_id']]['comps'][$l['comp_id']]['name'] = $l['comp_name'];
                $tab['wynik'][$l['city_id']]['comps'][$l['comp_id']]['code'] = $l['comp_code'];
                $tab['wynik'][$l['city_id']]['comps'][$l['comp_id']]['ligi'][$l['league_id']]['name'] = $l['league_name'];
                $tab['wynik'][$l['city_id']]['comps'][$l['comp_id']]['ligi'][$l['league_id']]['code'] = $l['league_code'];
            }
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_select_leagues($comp_id = null, $extra=0)
    {
        $this->db
                ->select('league_id, league_code, comp_code')
                ->order_by('comp_code','asc')
                ->order_by('league_code','asc');
        if(empty($comp_id))
            $wynik = $this->db->get('view_leagues');
        else
            $wynik = $this->db->get_where('view_leagues',array('comp_id'=>$comp_id));
        if($wynik->num_rows())
        {
            $tab['stan'] = TRUE;
            if($extra==1)
                foreach($wynik->result_array() as $l)
                    $tab['wynik'][$l['league_id']] = $l['league_code'].' ('.$l['comp_code'].')';
            else
                foreach($wynik->result_array() as $l)
                    $tab['wynik'][$l['league_id']] = $l['league_code'];
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_game($id)
    {
        $wynik = $this->db
                ->get_where('view_scores',array('game_id'=>$id));
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            $tab['wynik']= $wynik->row_array();
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_events()
    {
        $wynik = $this->db->get('ut_gameevents');
        if($wynik->num_rows()>0)
        {
            foreach($wynik->result_array() as $w)
            {
                $tab[$w['ge_id']]['name'] = $w['ge_name'];
                $tab[$w['ge_id']]['image']= $w['ge_image'];
                $tab[$w['ge_id']]['code'] = $w['ge_code'];
            }
            return $tab;
        }
        else
            return '';
    }
    
    public function get_team_players($gospid,$goscid)
    {
        $wynik = $this->db
                ->select('user_id, user_fname, user_lname, team_code')
                ->where('team_id',$gospid)
                ->or_where('team_id',$goscid)
                ->group_by('user_id')
                ->order_by('user_lname','ASC')
                ->order_by('user_fname','ASC')
                ->get('view_users');
        if($wynik->num_rows()>0)
        {
            foreach($wynik->result_array() as $w)
                $tab[$w['team_code']][$w['user_id']] = $w['user_lname'].' '.$w['user_fname'];
            return $tab;
        }
        else
            return '';
    }
    
    /*
     * Pobieranie listy miast z bazy danych systemu i zestawienie ich w formie tablicy
     * 
     * @return array
     * 
     */
    public function get_cities()
    {
        $wynik = $this->db->order_by('city_name')->get('ut_cities');
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $w)
                $tab['wynik'][$w['city_id']] = $w['city_name'];
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    /*
     * Pobieranie listy aktywnych rozgrywek ligowych
     * 
     * @param bool $typ     jeśli 1, to zwraca listę z pełnymi nazwami rozgrywek, a jeśli 0 to ze skróconymi
     * 
     * @return array
     */
    public function get_comps($typ = 1)
    {
        $wynik = $this->db
                ->join('ut_cities','ut_comps.comp_city=ut_cities.city_id','left')
                ->order_by('ut_cities.city_name','ASC')
                ->order_by('ut_comps.comp_name','ASC')
                ->get_where('ut_comps',array('ut_comps.comp_active'=>1));
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $w)
                if($typ==1)
                    $tab['wynik'][$w['comp_id']] = $w['comp_name'].' ('.$w['city_name'].')';
                else
                    $tab['wynik'][$w['comp_id']] = $w['comp_code'].' ('.$w['city_name'].')';
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_seasons()
    {
        $wynik = $this->db
                ->select('season_year')
                ->group_by('season_year')
                ->get('ut_seasons');
        if($wynik->num_rows()>0)
            foreach($wynik->result_array() as $w)
                $tab[$w['season_year']] = $w['season_year'];
        else
            $tab = '';
        return $tab;
    }
    
    public function get_league_table($id,$sezon='')
    {
        if(empty($sezon))
        {
            $sezon = $this->db->select_max('game_season')->get_where('ut_games',array('game_league'=>$id));
            $sezon = $sezon->row_array();
            $sezon = $sezon['game_season'];
            $wynik = $this->db->get_where('view_games',array('league_id'=>$id,'game_season'=>$sezon,'played'=>1));
        }
        else
            $wynik = $this->db->get_where('view_games',array('league_id'=>$id,'game_season'=>$sezon,'played'=>1));
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $w)
            {
                $tab['wynik']['comp'][$w['comp_id']]['name'] = $w['comp_name'];
                $tab['wynik']['comp'][$w['comp_id']]['code'] = $w['comp_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['name'] = $w['league_name'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['code'] = $w['league_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['sezon']= $w['game_season'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['id']      = $w['team_id']; 
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['name']    = $w['team_name'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['code']    = $w['team_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['logo']    = $w['team_logo'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalfor'] +=$w['goal_for'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalaga'] +=$w['goal_against'];
                switch($w['points'])
                {
                    case 3:
                        $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['wins'] += 1;
                        break;
                    case 1:
                        $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['draws']+= 1;
                        break;
                    case 0:
                        $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['loses']+= 1;
                        break;
                }
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['points']  +=$w['points'];
                if(!$w['postponed'])
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['played'] += 1;
            }
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_league_tables()
    {
        $sezon = $this->db->select_max('game_season')->get('ut_games');
        $sezon = $sezon->row_array();
        $sezon = $sezon['game_season'];
        $wynik = $this->db->get_where('view_games',array('game_season'=>$sezon,'played'=>1));
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $w)
            {
                $tab['wynik']['comp'][$w['comp_id']]['name'] = $w['comp_name'];
                $tab['wynik']['comp'][$w['comp_id']]['code'] = $w['comp_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['name'] = $w['league_name'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['code'] = $w['league_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['sezon']= $w['game_season'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['id']      = $w['team_id']; 
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['name']    = $w['team_name'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['code']    = $w['team_code'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['logo']    = $w['team_logo'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalfor'] +=$w['goal_for'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalaga'] +=$w['goal_against'];
                $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['points']  +=$w['points'];
                if(!$w['postponed'])
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['played'] += 1;
            }
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_fixtures($id,$season='')
    {
        if(empty($sezon))
        {
            $sezon = $this->db->select_max('game_season')->get('ut_games');
            $sezon = $sezon->row_array();
            $sezon = $sezon['game_season'];
            $wynik = $this->db->get_where('view_scores',array('league_id'=>$id,'game_season'=>$sezon));
        }
        else
            $wynik = $this->db->get_where('view_scores',array('league_id'=>$id,'game_season'=>$sezon));
        if($wynik->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($wynik->result_array() as $w)
            {
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['date'] = $w['game_date'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['hour'] = $w['game_hour'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['postponed']  = $w['game_postponed'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['played']     = $w['game_played'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosp']['id'] = $w['gosp_id'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosp']['name']   = $w['gosp_name'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosp']['code']   = $w['gosp_code'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosp']['logo']   = $w['gosp_logo'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosp']['goals']  = $w['gosp_for'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosc']['id']     = $w['gosc_id'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosc']['name']   = $w['gosc_name'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosc']['code']   = $w['gosc_code'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosc']['logo']   = $w['gosc_logo'];
                $tab['wynik'][$w['game_fixture']][$w['game_id']]['gosc']['goals']  = $w['gosc_for'];
            }
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_fixture($fixture)
    {
        if(is_array($fixture))
        {
            $wynik = $this->db
                    ->order_by('game_hour')
                    ->get_where('view_scores',$fixture);
            if($wynik->num_rows()>0)
            {
                $tab['stan'] = TRUE;
                $gosp = TRUE;
                foreach($wynik->result_array() as $w)
                {
                    $tab['wynik']['fixture']['number']      = $w['game_fixture'];
                    $tab['wynik']['fixture']['fixture_date']= $w['game_date'];
                    $tab['wynik']['fixture']['league_id']   = $w['league_id'];
                    $tab['wynik']['fixture']['league_name'] = $w['league_name'];
                    $tab['wynik']['fixture']['league_code'] = $w['league_code'];
                    $tab['wynik']['fixture']['comp_name']   = $w['comp_name'];
                    $tab['wynik']['fixture']['comp_code']   = $w['comp_code'];
                    $tab['wynik']['fixture']['game_season'] = $w['game_season'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['time']        = $w['game_hour'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['postponed']   = $w['game_postponed'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosp']['id']     = $w['gosp_id'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosp']['name']   = $w['gosp_name'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosp']['code']   = $w['gosp_code'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosp']['logo']   = $w['gosp_logo'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosp']['score']  = $w['gosp_for'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosc']['id']     = $w['gosc_id'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosc']['name']   = $w['gosc_name'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosc']['code']   = $w['gosc_code'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosc']['logo']   = $w['gosc_logo'];
                    $tab['wynik']['fixture']['games'][$w['game_id']]['teams']['gosc']['score']  = $w['gosc_for'];
                }
            }
            else
                $tab['stan'] = FALSE;
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    public function get_tables_by_user($uid)
    {
        $uteam = $this->db
                ->select('league_id, season_year')
                ->group_by('league_id')
                ->get_where('view_users',array('user_id'=>$uid));
        if($uteam->num_rows()>0)
        {
            $tab['stan'] = TRUE;
            foreach($uteam->result_array() as $u)
            {
                $wynik = $this->db->get_where('view_games',array('league_id'=>$u['league_id'],'game_season'=>$u['season_year'],'played'=>1));
                foreach($wynik->result_array() as $w)
                {
                    $tab['wynik']['comp'][$w['comp_id']]['name'] = $w['comp_name'];
                    $tab['wynik']['comp'][$w['comp_id']]['code'] = $w['comp_code'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['name'] = $w['league_name'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['code'] = $w['league_code'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['sezon']= $w['game_season'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['id']      = $w['team_id']; 
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['name']    = $w['team_name'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['code']    = $w['team_code'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['logo']    = $w['team_logo'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalfor'] +=$w['goal_for'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['goalaga'] +=$w['goal_against'];
                    $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['points']  +=$w['points'];
                    if(!$w['postponed'])
                        $tab['wynik']['comp'][$w['comp_id']]['league'][$w['league_id']]['teams'][$w['team_id']]['played'] += 1;
                }
            }
        }
        else
            $tab['stan'] = FALSE;
        return $tab;
    }
    
    /*
     * Sprawdzanie czy miasto o danej nazwie istnieje w bazie danych
     * 
     * @param string $name
     * @return bool
     */
    public function check_city($name)
    {
        $wynik = $this->db->get_where('ut_cities',array('city_name'=>$name));
        if($wynik->num_rows()>0)
            return TRUE;
        else
            return FALSE;
    }
    
    /*
     * Dodawanie miasta do bazy danych
     * 
     * @param array $tab
     * @return array
     */
    public function insert_city($tab)
    {
        $wynik = $this->db->insert('ut_cities',$tab);
        if($this->db->affected_rows()==1)
        {
            $ret['stan']= TRUE;
            $ret['id']  = $this->db->insert_id();
        }
        else
            $ret['stan']= FALSE;
        return $ret;
    }
    
    /*
     * Dodawanie rozgrywek do bazy danych
     * 
     * @param array $tab
     * @return bool
     */
    public function insert_comp($tab)
    {
        $wynik = $this->db->insert('ut_comps',$tab);
        if($this->db->affected_rows()==1)
            return TRUE;
        else
            return FALSE;
    }
    
    /*
     * dodawanie bramek z meczy do bazy danych
     * 
     * @param array $tab    - tablica z danymi o meczu
     * 
     * @return bool
     */
    public function update_match_info($tab,$game_id)
    {
        $this->db->where('game_id',$game_id);
        $this->db->update('ut_games',$tab);
        if($this->db->affected_rows()==1 || $this->db->affected_rows()==0)
            return TRUE;
        else
            return FALSE;
    }
    
    /*
     * dodawanie bramek z meczy do bazy danych
     * 
     * @param array $tab    - tablica z danymi o meczu
     * 
     * @return bool
     */
    public function insert_match_info($tab)
    {
        $this->db->insert('ut_games',$tab);
        if($this->db->affected_rows()==1)
            return TRUE;
        else
            return FALSE;
    }
    
    /*
     * dodawanie bramek z meczy do bazy danych
     * 
     * @param array $tab    - tablica z danymi o meczach
     * @param int   $count  - liczba meczy do dodania
     * 
     * @return bool
     */
    public function insert_scores($tab,$count)
    {
        $this->db->insert_batch('ut_gamescore',$tab);
        if($this->db->affected_rows()==$count)
            return TRUE;
        else
            return FALSE;
    }
    
    /*
     * dodawanie bramek z meczy do bazy danych
     * 
     * @param array $tab    - tablica z danymi o meczach
     * @param int   $count  - liczba meczy do dodania
     * 
     * @return bool
     */
    public function update_scores($tab,$count)
    {
        $state = TRUE;
        pretty_print($tab);
        foreach($tab as $game)
        {
            $this->db->where('gs_game',$game['gs_game']);
            $this->db->where('gs_team',$game['gs_team']);
            $this->db->update('ut_gamescore',$game);
            if($this->db->affected_rows()==0)
                $state = FALSE;
        }
        return $state;
    }
    
    public function check_game_id($id)
    {
        $wynik = $this->db->get_where('view_scores',array('game_id'=>$id));
        if($wynik->num_rows===1)
            return TRUE;
        else
            return FALSE;
    }
    
    public function check_team_id($id,$typ)
    {
        $wynik = $this->db->get_where('ut_team',array('team_id'=>$id));
        if($wynik->num_rows===1)
            return TRUE;
        else
            return FALSE;
    }
    
    public function check_league_id($id,$typ)
    {
        $wynik = $this->db->get_where('ut_leagues',array('team_id'=>$id,'league_active'=>1));
        if($wynik->num_rows===1)
            return TRUE;
        else
            return FALSE;
    }
    
    public function set_game_played($id)
    {
        $tab['game_played']     = 1;
        $tab['game_postponed']  = 0;
        $this->db
                ->where('game_id',$id)
                ->update('ut_games',$tab);
    }
    
    public function set_game_postponed($id)
    {
        $tab['game_postponed']  = 1;
        $tab['game_played']     = 0;
        $this->db
                ->where('game_id',$id)
                ->update('ut_games',$tab);
    }
    
    public function update_game($batch,$id)
    {
        $wynik = $this->db->get_where('ut_gamescore',array('gs_game'=>$id));
        if($wynik->num_rows()>0)
            $this->db->update_batch('ut_gamescore',$batch,'gs_game');
        else
            $this->db->insert_batch('ut_gamescore',$batch);
        if($this->db->affected_rows()==2)
            return TRUE;
        else
            return FALSE;
    }
}